package mysql

import (
	"chart.zozoo.net/core/conf"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var MysqlClient *gorm.DB

const (
	dbTimeOut      = 5000 //ms
	dbWriteTimeout = 5000 //ms
	dbReadTimeout  = 5000
)

func ConnMysql(cfg *conf.Mysql) *gorm.DB {
	timeout := cfg.Timeout
	if timeout < 0 {
		timeout = dbTimeOut
	}
	WriteTimeOut := cfg.WriteTimeOut
	if WriteTimeOut < 0 {
		WriteTimeOut = dbWriteTimeout
	}
	ReadTimeOut := cfg.ReadTimeOut
	if ReadTimeOut < 0 {
		ReadTimeOut = dbReadTimeout
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local&"+
		"timeout=%dms&writeTimeout=%dms&readTimeout=%dms",
		cfg.Username,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.Database,
		cfg.Charset,
		timeout,
		WriteTimeOut,
		ReadTimeOut,
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}

	//数据库池配置
	sqlDb, err := db.DB()
	if err != nil {
		panic(err)
	}
	sqlDb.SetMaxIdleConns(cfg.MaxIdleConns) //空闲连接数
	sqlDb.SetMaxOpenConns(cfg.MaxOpenConns) //最大连接数

	MysqlClient = db
	return db
}
